﻿---@diagnostic disable: trailing-space
local extension = Package:new("rfenghou_cards", Package.CardPack)
extension.extensionName = "aaa_fenghou"

Fk:loadTranslationTable{
  ["rfenghou_cards"] = "封侯卡牌",
}

local U = require "packages/utility/utility"

--[[

  基本牌

]]--

local shadeSkill = fk.CreateActiveSkill{  --祭祀智慧之不想带江山如故还引用影
  name = "rfenghou__shade_skill",
  can_use = Util.FalseFunc,
}
local shade = fk.CreateBasicCard{
  name = "&rfenghou__shade",
  suit = Card.Spade,
  number = 1,
  skill = shadeSkill,
}
extension:addCard(shade)
Fk:loadTranslationTable{
  ["shade"] = "影",
  ["rfenghou__shade"] = "影",
  [":rfenghou__shade"] = "基本牌<br/><b>效果</b>：没有效果，不能被使用。<br/>当【影】进入弃牌堆后移出游戏。<br/>当一名角色获得【影】时，"..
  "均为从游戏外获得♠A的【影】。",
}

local premeditate = fk.CreateDelayedTrickCard{  --祭祀智慧之不想带江山如故还引用蓄谋
  name = "&rfenghou__premeditate",
}
extension:addCard(premeditate)
Fk:loadTranslationTable{
  ["premeditate"] = "蓄谋",
  ["rfenghou__premeditate"] = "蓄谋",
  [":rfenghou__premeditate"] = "这张牌视为延时锦囊<br/><b>效果：</b>判定阶段开始时，按置入顺序（后置入的先处理）依次处理“蓄谋”牌：1.使用此牌，"..
  "然后此阶段不能再使用此牌名的牌；2.将所有“蓄谋”牌置入弃牌堆。",
}

local drugs_skill = fk.CreateActiveSkill{
  name = "drugs_skill",
  prompt = "#drugs_skill",
  mod_target_filter = Util.TrueFunc,
  can_use = function(self, player, card)
    return not player:isProhibited(player, card)
  end,
  on_use = function(self, room, cardUseEvent)
    if not cardUseEvent.tos or #TargetGroup:getRealTargets(cardUseEvent.tos) == 0 then
      cardUseEvent.tos = { { cardUseEvent.from } }
    end
  end,
  on_effect = function(self, room, effect)
    local to = room:getPlayerById(effect.to)
    if to.dead then return end
    if to:isWounded() then
      room:recover { num = 1, skillName = self.name, who = to, recoverBy = room:getPlayerById(effect.from), card = effect.card }
      if to.dead then return end
      room:addPlayerMark(to, "@drugsInflicted")
    end
    if not to:isWounded() then
      room:addPlayerMark(to, "drugs_buff-phase")
    end
  end
}

local drugs = fk.CreateBasicCard{
  name = "drugs",
  suit = Card.Spade,
  number = 1,
  skill = drugs_skill,
} 

local drugs_trigger = fk.CreateTriggerSkill{
  name = "#drugs_trigger",
  global = true,
  mute = true,
  priority = 0.01,
  frequency = Skill.Compulsory,
  events = {fk.DamageInflicted, fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    if target == player then
      if event == fk.DamageInflicted then
        return player:getMark("@drugsInflicted") > 0
      else
        return player:getMark("@drugsCaused") > 0
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DamageInflicted then
      data.damage = data.damage + player:getMark("@drugsInflicted")
      room:setPlayerMark(player, "@drugsInflicted", 0)
    else
      data.damage = data.damage + player:getMark("@drugsCaused")
      room:setPlayerMark(player, "@drugsCaused", 0)
    end
  end,
}
Fk:addSkill(drugs_trigger)

local drugs_targetmod = fk.CreateTargetModSkill{
  name = "drugs_targetmod",
  global = true,
  residue_func = function(self, player, skill, scope)
    if skill then
      if skill.trueName == "slash_skill" or skill.trueName == "analeptic_skill" then
        return player:getMark("drugs_buff-phase")
      end 
    end
  end,
}
Fk:addSkill(drugs_targetmod)

extension:addCards({
  drugs,
  drugs:clone(Card.Club, 1),
  drugs:clone(Card.Diamond, 1),
  drugs:clone(Card.Heart, 1),
})

Fk:loadTranslationTable{
  ["drugs"] = "散",
	[":drugs"] = "基本牌<br /><b>时机</b>：出牌阶段<br /><b>目标：</b>你<br /><b>效果：</b>若你已受伤，回复1点体力且下次受到的伤害+1。若你未受伤，或因此回复至满血，本阶段使用【杀】与【酒】次数+1。",
  ["drugs_skill"] = "散",
  ["#drugs_skill"] = "已受伤：回复体力且下次受到伤害+1；未受伤/因此回满血：使用【杀】与【酒】次数+1",
  ["@drugsInflicted"] = "散:受伤+",
  ["#drugs_trigger"] = "散",
}


local old__drugs_skill = fk.CreateActiveSkill{
  name = "old__drugs_skill",
  prompt = "#old__drugs_skill",
  mod_target_filter = Util.TrueFunc,
  can_use = function(self, player, card)
    return not player:isProhibited(player, card)
  end,
  on_use = function(self, room, cardUseEvent)
    if not cardUseEvent.tos or #TargetGroup:getRealTargets(cardUseEvent.tos) == 0 then
      cardUseEvent.tos = { { cardUseEvent.from } }
    end
  end,
  on_effect = function(self, room, effect)
    local to = room:getPlayerById(effect.to)
    if to.dead then return end
    if to:isWounded() then
      room:recover { num = 1, skillName = self.name, who = to, recoverBy = room:getPlayerById(effect.from) }
      if to.dead then return end
      room:addPlayerMark(to, "@drugsInflicted")
    end
    if not to:isWounded() then
      room:addPlayerMark(to, "@drugsCaused")
    end
  end
}

local old__drugs = fk.CreateBasicCard{
  name = "&old__drugs",
  suit = Card.Spade,
  number = 1,
  skill = old__drugs_skill,
} 

extension:addCards({
  old__drugs
})

Fk:loadTranslationTable{
  ["old__drugs"] = "散",
	[":old__drugs"] = "基本牌（衍生牌）<br /><b>时机</b>：出牌阶段<br /><b>目标：</b>你<br /><b>效果：</b>若你已受伤，回复1点体力且下次受到的伤害+1。若你未受伤，或因此回复至满血，下次造成伤害+1。",
  ["old__drugs_skill"] = "散",
  ["#old__drugs_skill"] = "已受伤：回复体力且下次受到伤害+1；未受伤/因此回满血：下次造成伤害+1",
  ["@drugsCaused"] = "散:造伤+",
}

local diceSkill = fk.CreateActiveSkill{
  name = "rfenghou__dice_skill",
  can_use = Util.FalseFunc,
}
local dice = fk.CreateBasicCard{
  name = "&dice",
  suit = Card.Spade,
  number = 1,
  skill = diceSkill,
}
extension:addCard(dice)
Fk:loadTranslationTable{
  ["dice"] = "骰",
  [":dice"] = "基本牌<br/><b>效果</b>：没有效果，仅用于丢骰子。",
}

local wild_revolt_skill = fk.CreateActiveSkill{
  name = "wild_revolt_skill",
  prompt = "#wild_revolt_skill",
  can_use = Util.GlobalCanUse,
  on_use = Util.GlobalOnUse,
  mod_target_filter = Util.TrueFunc,
  on_action = function(self, room, use, finished)
    use.extra_data = use.extra_data or {}
    if not finished then
      use.extra_data.WildRevoltInfo = {}
    else
      local info = use.extra_data.WildRevoltInfo
      if info then
        local targets = table.map(table.filter(use.extra_data.WildRevoltInfo, function(id) return id ~= 0 end), Util.Id2PlayerMapper)
        local bad = #targets > (#info / 2)
        use.extra_data.WildRevoltInfo = nil
        for _, p in ipairs(targets) do
          if not p.dead then
            if bad then
              room:damage { from = nil, to = p, damage = 1, skillName = self.name, card = use.card }
            else
              local tos = room:askForChoosePlayers(p, table.map(room.alive_players, Util.IdMapper), 1, 1, "#wild_revolt-choose",
              self.name, false)
              room:damage { from = p, to = room:getPlayerById(tos[1]), damage = 1, skillName = self.name, card = use.card }
            end
          end
        end
      end
    end
  end,
  on_effect = function(self, room, effect)
    local to = room:getPlayerById(effect.to)
    if effect.extra_data and effect.extra_data.WildRevoltInfo then
      if room:askForSkillInvoke(to, self.name, nil, "#wild_revolt-ask") then
        table.insert(effect.extra_data.WildRevoltInfo, to.id)
      else
        table.insert(effect.extra_data.WildRevoltInfo, 0)
      end
    end
  end
}

local wild_revolt = fk.CreateTrickCard{
  name = "wild_revolt",
  suit = Card.Spade,
  number = 13,
  multiple_targets = true,
  is_damage_card = true,
  skill = wild_revolt_skill,
}

extension:addCard(wild_revolt)

Fk:loadTranslationTable{
  ["wild_revolt"] = "群逆纵逸",
	[":wild_revolt"] = "锦囊牌<br /><b>时机</b>：出牌阶段<br /><b>目标：</b>所有角色<br /><b>效果：</b>目标角色秘密选择是否于结算后分配1点伤害，若选择是的数量多于一半，改为受到伤害。",
  ["wild_revolt_skill"] = "群逆纵逸",
  ["#wild_revolt_skill"] = "令所有角色选择是否分配伤害，若选择是的角色多于一半，改为受到伤害",
  ["#wild_revolt-ask"] = "群逆纵逸:是否选择在结算后分配1点伤害？",
  ["#wild_revolt-choose"] = "群逆纵逸:请分配1点伤害！",
}


---FIXEME: 此乃【晋】桓温的技能【行将】，由于卡牌加载顺序问题无奈放置于此，待更好的方案后移出

local names = {}
for name, _ in pairs(Fk.all_card_types) do
  table.insertIfNeed(names, name)
end
for _, card in ipairs(extension.cards) do
  table.insertIfNeed(names, card.name)
end

for _, name in ipairs(names) do
  local nameZh = Fk:translate(name, "zh_CN")
  local nameAbbr = nameZh
  local len = nameAbbr:len()
  if len == 1 then
    nameAbbr = "印"..nameAbbr
  elseif len > 2 then
    nameAbbr = string.sub(nameAbbr, 1, 6)
  end
  local desc = "每回合一次，你可以视为使用【"..nameZh.."】。"
  local xingjiangSkill = fk.CreateViewAsSkill{
    name = "rfenghou__xingjiang_"..name,
    pattern = name,
    card_filter = Util.FalseFunc,
    prompt = desc,
    view_as = function(self)
      local c = Fk:cloneCard(self.name:gsub("rfenghou__xingjiang_", ""))
      c.skillName = self.name
      c.color = Card.NoColor
      c.suit = Card.NoSuit
      c.number = 0
      return c
    end,
    before_use = function (self, player, use)
      player:broadcastSkillInvoke("rfenghou__xingjiang")
    end,
    enabled_at_play = function(self, player)
      return player:usedSkillTimes(self.name) == 0
    end,
    enabled_at_response = function (self, player, response)
      return not response and player:usedSkillTimes(self.name) == 0
    end,
    on_lose = function (self, player)
      player:setSkillUseHistory(self.name, 0, Player.HistoryTurn)
    end,
  }
  Fk:addSkill(xingjiangSkill)
  
  Fk:loadTranslationTable{
    [xingjiangSkill.name] = nameAbbr,
    [":"..xingjiangSkill.name] = desc,
  }
end


local cicada_temples_skill = fk.CreateTriggerSkill{
  name = "#cicada_temples_skill",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    for _, id in ipairs(player:getCardIds("e")) do
      local card = Fk:getCardById(id)
      if card.name == "cicada_temples" then
        player:drawCards(math.min(card:getMark("cicada_temples_count") + 1, 3), self.name)
        if player.dead then break end
      end
    end
  end,

  refresh_events = {fk.AfterTurnEnd},
  can_refresh = function (self, event, target, player, data)
    return table.find(player:getCardIds("e"), function (id)
      return Fk:getCardById(id).name == "cicada_temples"
    end)
  end,
  on_refresh = function(self, event, target, player, data)
    for _, id in ipairs(player:getCardIds("e")) do
      local card = Fk:getCardById(id)
      if card.name == "cicada_temples" then
        player.room:setCardMark(card, "cicada_temples_count", card:getMark("cicada_temples_count") + 1)
      end
    end
  end,
}
Fk:addSkill(cicada_temples_skill)

local cicada_temples = fk.CreateTreasure{
  name = "&cicada_temples",
  suit = Card.Club,
  number = 12,
  equip_skill = cicada_temples_skill,
  ---@param room Room
  on_uninstall = function(self, room, player)
    Treasure.onUninstall(self, room, player)
    room:setCardMark(self, "cicada_temples_count", 0)
  end,
}
extension:addCard(cicada_temples)

Fk:loadTranslationTable{
  ["cicada_temples"] = "蝉鬓",
  [":cicada_temples"] = "装备牌·宝物（衍生牌）<br/><b>宝物技能</b>：锁定技，结束阶段，你摸X张牌（X为此牌进入你装备区后经过的回合数，至多为3）。此牌进入弃牌堆后销毁。",
  ["#cicada_temples_skill"] = "蝉鬓",
}

return extension
